import {
  Button,
  Card,
  Col,
  Form,
  Input,
  Row,
  Select,
} from 'antd';
import React, { Component, Fragment } from 'react';

import { Dispatch } from 'redux';
import { FormComponentProps } from 'antd/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { SorterResult } from 'antd/es/table';
import { connect } from 'dva';
import { StateType } from './model';
import StandardTable, { StandardTableColumnProps } from './components/StandardTable';
import OutbuyInfoForm, { FormValsType } from './components/OutbuyInfoForm';
import { TableListItem, TableListPagination, TableListParams } from './data.d';
import { download } from '../foreignTraderQuery/utils/commons';
import styles from './style.less';
import router from 'umi/router';
import Constants from '../foreignTraderQuery/utils/Constants';
var statusArr = ['未知', '待支付', '待跟进', '已完成'];

const FormItem = Form.Item;
const { Option } = Select;
const getValue = (obj: { [x: string]: string[] }) =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

interface TableListProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  loading: boolean;
  foreignTraderQuery: StateType;
}

interface TableListState {
  modalVisible: boolean;
  updateModalVisible: boolean;
  selectedRows: TableListItem[];
  formValues: { [key: string]: string };
  recordFormValues: Partial<TableListItem>;
  index: number;
  countrycode: string;
}

/* eslint react/no-multi-comp:0 */
@connect(
  ({
    foreignTraderQuery,
    loading,
    global,
  }: {
    foreignTraderQuery: StateType;
    global: StateType;
    loading: {
      models: {
        [key: string]: boolean;
      };
    };
  }) => ({
    foreignTraderQuery,
    global,
    loading: loading.models.rule,
    load: loading.models.foreignTraderQuery,
  }),
)
class TableList extends Component<TableListProps, TableListState> {
  state: TableListState = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    recordFormValues: {},
    index: null,
    countrycode: null,
    recordFlag: false,
  };

  columns: StandardTableColumnProps[] = [
    {
      title: '目标公司名称',
      dataIndex: 'name',
    },
    {
      title: '所在地址',
      dataIndex: 'address',
    },
    {
      title: '邮政编码',
      dataIndex: 'zipCode',
    },
    {
      title: '操作',
      render: (text, record, index) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record, index)}>查看</a>
        </Fragment>
      ),
    },
  ];

  recordColumns: StandardTableColumnProps[] = [
    {
      title: '申请单号',
      dataIndex: 'id',
      render: (text, record) => {
        return `ZBT-CR-${record.id}`;
      },
    },
    {
      title: '买家名称',
      dataIndex: 'buyer',
    },
    {
      title: '国家和地区编码',
      dataIndex: 'countrycode',
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (text, record) => {
        return statusArr[record.status];
      },
    },
    {
      title: '操作',
      render: (text, record, index) => (
        <Fragment>
          {record.reportUrl ? <a onClick={() => this.onDownload(record)}>下载报告</a> : ''}
          {record.status === '1' ? <a onClick={() => this.goPay(record)}>支付</a> : ''}
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({ type: 'foreignTraderQuery/getCrifAreaList', payload: {} });
  }

  handleStandardTableChange = (
    pagination: Partial<TableListPagination>,
    filtersArg: Record<keyof TableListItem, string[]>,
    sorter: SorterResult<TableListItem>,
  ) => {
    const { dispatch } = this.props;
    const { formValues, recordFlag } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params: Partial<TableListParams> = {
      page: pagination.current,
      size: pagination.pageSize,
      ...formValues,
      //...filters,
    };
    // if (sorter.field) {
    //   params.sorter = `${sorter.field}_${sorter.order}`;
    // }

    if (recordFlag) {
      dispatch({
        type: 'foreignTraderQuery/getRecerdsList',
        payload: params,
      });
    } else {
      dispatch({
        type: 'foreignTraderQuery/fetch',
        payload: params,
      });
    }
  };

  handleSelectRows = (rows: TableListItem[]) => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = () => {
    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
        recordFlag: false,
      });

      let params = {
        page: 1,
        size: 10,
        ...values,
      };

      dispatch({
        type: 'foreignTraderQuery/refreshState',
        payload: {
          list: [],
          pageListData: [],
        },
      });

      dispatch({
        type: 'foreignTraderQuery/fetch',
        payload: params,
      });
    });
  };

  handleRecord = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({ recordFlag: true });

    dispatch({
      type: 'foreignTraderQuery/getRecerdsList',
      payload: {
        page: 1,
        size: 10,
      },
    });
  };

  handleModalVisible = (flag?: boolean, record?: FormValsType, index) => {
    const {
      form: { getFieldValue },
      dispatch,
    } = this.props;
    let countryCode = getFieldValue('countryCode')
      ? getFieldValue('countryCode')
      : this.state.countrycode;

    if (flag) {
      dispatch({
        type: 'foreignTraderQuery/getPrice',
        payload: {
          country: countryCode ? countryCode : record.countryCode,
        },
      });
    }

    this.setState({
      modalVisible: !!flag,
      recordFormValues: record || {},
      index: index,
      countrycode: countryCode,
    });
  };

  onDownload = record => {
    let url = PORTAL_PATH + '/api/file/download?filename=' + record.reportUrl;
    download(url, {});
  };

  goPay = record => {
    if (record.id) {
      router.push(
        '/pay/payConfirm?goodsId=' +
          Constants.NUMBER_SIX +
          '&entityid=' +
          record.id +
          '&bussinesstype=' +
          Constants.SERVICE.OUTBUYER_SERVICE +
          '&extra=' +
          record.countrycode,
      );
    }
  };

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator, getFieldValue },
      foreignTraderQuery: { crifCountrys, crifRegions },
    } = this.props;
    return (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="国家和地区">
              {getFieldDecorator('countryCode', {
                rules: [{ required: true, message: '请选择国家和地区！' }],
                initialValue: '',
              })(
                <Select
                  style={{ width: '100%' }}
                  showSearch
                  placeholder="可通过输入关键字搜索"
                  filterOption={(input, option) =>
                    option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {crifCountrys.length < 1
                    ? []
                    : crifCountrys.map(item => {
                        return (
                          <Select.Option value={item.code} key={item.code}>
                            {item.nameCn}
                          </Select.Option>
                        );
                      })}
                </Select>,
              )}
            </FormItem>
          </Col>
          {getFieldValue('countryCode').includes('USA', 'CAN') ? (
            <Col md={8} sm={24}>
              <FormItem label="州">
                {getFieldDecorator('regionCode', {
                  rules: [
                    {
                      required: getFieldValue('countryCode').includes('USA', 'CAN'),
                      message: '请选择国家和地区！',
                    },
                  ],
                  initialValue: '',
                })(
                  <Select
                    style={{ width: '100%' }}
                    showSearch
                    placeholder="可通过输入关键字搜索"
                    filterOption={(input, option) =>
                      option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {crifRegions.length < 1
                      ? []
                      : crifRegions.map(item => {
                          return (
                            <Select.Option value={item.code} key={item.code}>
                              {item.nameCn}
                            </Select.Option>
                          );
                        })}
                  </Select>,
                )}
              </FormItem>
            </Col>
          ) : (
            ''
          )}
          <Col md={8} sm={24}>
            <FormItem label="目标公司">
              {getFieldDecorator('company', {
                rules: [{ required: true, message: '请输入目标公司名称！' }],
                initialValue: '',
              })(<Input placeholder="目标公司名称" />)}
            </FormItem>
          </Col>
        </Row>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'left', marginBottom: 24 }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={this.props.load}
              onClick={this.handleSearch}
            >
              查询
            </Button>
            <Button icon="file-search" style={{ marginLeft: 8 }} onClick={this.handleRecord}>
              购买记录
            </Button>
          </div>
        </div>
      </Form>
    );
  }

  renderForm() {
    return this.renderAdvancedForm();
  }

  render() {
    const {
      foreignTraderQuery: { list, pagination, pageListData, recordList, recordPage },
      loading,
      dispatch,
    } = this.props;
    const data = { list: pageListData, pagination };
    const recordData = { list: recordList, pagination: recordPage };

    const {
      selectedRows,
      modalVisible,
      updateModalVisible,
      recordFormValues,
      index,
      countrycode,
      recordFlag,
    } = this.state;

    const methods = {
      handleModalVisible: this.handleModalVisible,
      handleSearch: this.handleSearch,
    };
    return (
      <PageHeaderWrapper>
        <Card bordered={false}>
          {modalVisible ? (
            <OutbuyInfoForm
              {...methods}
              {...this.props.foreignTraderQuery}
              dispatch={dispatch}
              updateModalVisible={updateModalVisible}
              recordFormValues={recordFormValues}
              index={index}
              countrycode={countrycode}
            />
          ) : (
            <div className={styles.tableList}>
              <div className={styles.tableListForm}>{this.renderForm()}</div>
              <StandardTable
                selectedRows={selectedRows}
                loading={loading}
                data={recordFlag ? recordData : data}
                columns={recordFlag ? this.recordColumns : this.columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
              />
            </div>
          )}
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default Form.create<TableListProps>()(TableList);
